//
// Created by martin on 10/18/21.
//

#include "pthread_once.h"
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/syscall.h>

struct _obj {
    int counter;
}obj;

static pthread_once_t init_create = PTHREAD_ONCE_INIT;
static struct _obj *objptr = NULL;
static int call_counter = 0;

__thread thread_id = 0;

static pid_t gettid()
{
    return syscall(SYS_gettid);
}

int get_thread_id()
{
    if (thread_id == 0) {
        thread_id = gettid();
    }

    return thread_id;
}

static void _init()
{
    objptr = malloc(sizeof(obj));
    if (!objptr) {
        char buf[256];
        strerror_r(errno, buf, sizeof(buf));
        fprintf(stderr, "thread%d: malloc obj error: %s\n", get_thread_id(), buf);
        return;
    }
    memset(objptr, 0, sizeof(obj));

    call_counter++;
}

void obj_create()
{
    pthread_once(&init_create, _init);
    objptr->counter++;

    printf("thread%d: _init called counter = %d\n", get_thread_id(), call_counter);
    printf("thread%d: create counter = %d\n", get_thread_id(), objptr->counter);
}
